package com.itjeffrey.autocode.security;

import com.alibaba.fastjson.JSON;
import com.itjeffrey.autocode.config.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 自定义 Security 权限注解实现
 * Author: admin
 */
//@Component //暂时关闭
public class SecurityPermissionSupport implements PermissionEvaluator {

    public static final Logger log = LoggerFactory.getLogger(SecurityPermissionSupport.class);

    @Resource
    private SecurityProperties securityProperty;

    /**
     * 自定义 Security 权限认证 @hasPermission
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        log.info("SecurityPermissionSupport hasPermission method is executing, Current Permission : {}",
                permission == null ? "null" : JSON.toJSONString(permission));
        JwtUserDetails securityUserDetails = (JwtUserDetails) authentication.getPrincipal();
        if (securityProperty.isEnableAdmin() && securityProperty.getAdminAcc().equals(securityUserDetails.getUsername())) {
            return true;
        }
        Collection<? extends GrantedAuthority> authorities = securityUserDetails.getAuthorities();
        Set<String> permissions = new HashSet<>();
        for (GrantedAuthority authority : authorities) {
            permissions.add(authority.getAuthority());
        }
        log.info("Current User has Permission Sizes : {}", permissions.size());
        return permissions.contains(permission);
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
